package org.dromara.legal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.legal.domain.Consult;
import org.dromara.legal.domain.Revert;
import org.dromara.legal.domain.bo.RevertBo;
import org.dromara.legal.domain.vo.ConsultVo;
import org.dromara.legal.domain.vo.LawyerVo;
import org.dromara.legal.domain.vo.RevertVo;
import org.dromara.legal.mapper.ConsultMapper;
import org.dromara.legal.mapper.LawyerMapper;
import org.dromara.legal.mapper.RevertMapper;
import org.dromara.legal.service.IRevertService;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysOssService;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 回复Service业务层处理
 *
 * @author zhuqingrun
 * @date 2024-10-15
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class RevertServiceImpl implements IRevertService {

    private final RevertMapper baseMapper;

    private final ConsultMapper consultMapper;

    private  final LawyerMapper lawyerMapper;

    private final ISysUserService sysUserService;

    private final ISysOssService sysOssService;

    private final SysUserMapper sysUserMapper;

    /**
     * 查询回复
     *
     * @param id 主键
     * @return 回复
     */
    @Override
    public RevertVo queryById(Long id){
        RevertVo revertVo = baseMapper.selectVoById(id);

        if (revertVo.getFile() != null){
            String[] split = revertVo.getFile().split(",");
            // String[] split 转 List<Long>
            List<Long> longs = new ArrayList<>();
            for (String s : split) {
                longs.add(Long.valueOf(s));
            }
            List<SysOssVo> sysOssVos = sysOssService.listByIds(longs);
            revertVo.setFileList(sysOssVos);
        }else {
            revertVo.setFileList(new ArrayList<>());
        }
        ConsultVo consultVo = consultMapper.selectVoById(revertVo.getConsultId());
        if (ObjectUtil.isNull(consultVo)){
            throw new ServiceException("咨询不存在");
        }
        SysUserVo sysUserVo = sysUserMapper.selectVoById(consultVo.getLawyerId());
        revertVo.setConsultVo(consultVo);
        revertVo.setSysUserVo(sysUserVo);
        return revertVo;
    }

    /**
     * 分页查询回复列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 回复分页列表
     */
    @Override
    public TableDataInfo<RevertVo> queryPageList(RevertBo bo, PageQuery pageQuery) {
        String userType = LoginHelper.getLoginUser().getUserType();
        if(userType.equals(UserType.APP_USER.getUserType())) {
            Map<String, Object> params = bo.getParams();
            // 设置查询已经审核通过的回复
            params.put("isQueryPass", true);
            bo.setParams(params);
        }
        LambdaQueryWrapper<Revert> lqw = buildQueryWrapper(bo);
        Page<RevertVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<RevertVo> records = result.getRecords();
        if(records.size() > 0){
            for (RevertVo record : records) {
                Long consultId = record.getConsultId();
                ConsultVo consultVo = consultMapper.selectVoById(consultId);
                SysUserVo sysUserVo = sysUserService.selectUserById(consultVo.getLawyerId());
                record.setSysUser(sysUserVo);
                if (record.getFile() != null){
                    String[] split = record.getFile().split(",");
                    // String[] split 转 List<Long>
                    List<Long> longs = new ArrayList<>();
                    for (String s : split) {
                        longs.add(Long.valueOf(s));
                    }
                    List<SysOssVo> sysOssVos = sysOssService.listByIds(longs);
                    record.setFileList(sysOssVos);
                }else {
                    record.setFileList(new ArrayList<>());
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的回复列表
     *
     * @param bo 查询条件
     * @return 回复列表
     */
    @Override
    public List<RevertVo> queryList(RevertBo bo) {
        LambdaQueryWrapper<Revert> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Revert> buildQueryWrapper(RevertBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Revert> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getConsultId() != null, Revert::getConsultId, bo.getConsultId());
        lqw.like(StringUtils.isNotBlank(bo.getReContent()), Revert::getReContent, bo.getReContent());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Revert::getStatus, bo.getStatus());
        lqw.eq(ObjectUtil.isNotNull(params.get("isQueryPass")),Revert::getStatus, "1");
        lqw.eq(StringUtils.isNotBlank(bo.getReImg()), Revert::getReImg, bo.getReImg());
        lqw.eq(StringUtils.isNotBlank(bo.getFile()), Revert::getFile, bo.getFile());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
            Revert::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(Revert::getCreateTime);
        return lqw;
    }

    /**
     * 新增回复
     *
     * @param bo 回复
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(RevertBo bo) {
        Revert add = MapstructUtils.convert(bo, Revert.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 发送短信通知审核员审核
            String templateId = "SMS_475190348";
            SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
            LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
            SmsResponse smsResponse = smsBlend.sendMessage("18801530129", templateId, map);
            if (!smsResponse.isSuccess()) {
                log.error("验证码短信发送异常 => {}", smsResponse);
            }
        }
        return flag;
    }

    /**
     * 修改回复
     *
     * @param bo 回复
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(RevertBo bo) {
        Revert update = MapstructUtils.convert(bo, Revert.class);
        validEntityBeforeSave(update);
        int i = baseMapper.updateById(update);
        if(bo.getStatus().equals("1")){
            UpdateWrapper<Consult> consultUpdateWrapper = new UpdateWrapper<>();
            consultUpdateWrapper.set("status","1");
            consultUpdateWrapper.eq("id",bo.getConsultId());
            consultMapper.update(consultUpdateWrapper);
        }
        if(bo.getStatus().equals("2")){
            ConsultVo consultVo = consultMapper.selectVoById(bo.getConsultId());
            SysUserVo sysUserVo = sysUserMapper.selectVoById(consultVo.getLawyerId());
            if (sysUserVo == null){
                log.error("未查询到相关该律师信息，或该律师已被删除");
                throw new ServiceException("未查询到相关该律师信息，或该律师已被删除");
            }
            // 发送审核未通过短信给律师
            String templateId = "SMS_475150403";
            LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
            SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
            SmsResponse smsResponse = smsBlend.sendMessage(sysUserVo.getPhonenumber(), templateId, map);
            if (!smsResponse.isSuccess()) {
                log.error("验证码短信发送异常 => {}", smsResponse);
            }
        }
        return  i > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Revert entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除回复信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
